#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <time.h>

#include "scheduler.h"

time_t base_time = 0;
SchedulerHandler scheduler = {0};
SchedulerTaskHandler *task1 = NULL;

/**
 * Expect Outputs:
 *  Begin 0s
 *  Run Task1 At 1s
 *  Run Task1 At 2s
 *  Run Task2 At 3s
 *  Run Task1 At 3s
 *  Run Task1 At 4s
 *  Run Task1 At 5s
 *  Run Task3 At 5s
 *  Run Task2 At 6s
 *  Run Task4 At 7s
 *  Run Task4 At 9s
 *  Run Task2 At 9s
 *  Finish 10s
 */

void Task1(void *arg);
void Task2(void *arg);
void Task3(void *arg);
void Task4(void *arg);

time_t run_time(void);

int main()
{
    base_time = time(NULL);
    time_t finish_time = base_time + 10;

    SchedulerInit(&scheduler);
    task1 = SchedulerAddTask(&scheduler, Task1, NULL, 0, 1);
    SchedulerAddTask(&scheduler, Task2, NULL, 0, 3);
    SchedulerAddTask(&scheduler, Task3, NULL, 5, 0);

    printf("Begin %llds\n", run_time());
    while (finish_time > time(NULL))
    {
        SchedulerTick(&scheduler);
    }
    printf("Finish %llds\n", run_time());

    return 0;
}

SchedulerTaskTick SchedulerGetTick(void)
{
    return ((uint32_t)time(NULL));
}

time_t run_time(void)
{
    return time(NULL) - base_time;
}

void run_task(uint8_t task_id)
{
    printf("Run Task%u At %llds\n", task_id, run_time());
}

void Task1(void *arg)
{
    run_task(1);
}

void Task2(void *arg)
{
    run_task(2);
}

void Task3(void *arg)
{
    run_task(3);

    SchedulerRemoveTask(task1);
    SchedulerAddTask(&scheduler, Task4, NULL, 0, 2);
}

void Task4(void *arg)
{
    run_task(4);
}
